package cn.tedu.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import sun.font.Script;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {

    public static void main(String[] args) {
        SpringApplication.run(DbInitApplication.class, args);
    }

    @Autowired
    private DataSource ds;

    @PostConstruct
    public void execSql() throws SQLException {
        run("sql/account.sql");
        run("sql/order.sql");
        run("sql/seata-server.sql");
        run("sql/storage.sql");
    }

    public void run(String file) throws SQLException {
        //sql文件路径封装成资源对象
        ClassPathResource cpr = new ClassPathResource(file,
                DbInitApplication.class.getClassLoader());
        //资源对象,封装成编码处理的资源对象
        EncodedResource resource = new EncodedResource(cpr);
        //链接数据库,执行sql脚本文件
        ScriptUtils.executeSqlScript(ds.getConnection(),resource);
    }
}
